// cd /projects/data_commons/cw_code/
// qstata cw_ind_sect_1_jsung.do &

di "Started at $S_DATE $S_TIME"

global dir_cw = "/projects/data_commons/cw/"
global ds_cw "${dir_cw}/cw_ind_sect"

clear
gen sector = .
gen newsitc = .
set obs 15


capture program drop fl_ind_sect
program fl_ind_sect
  args i_n i_sect i_ind
  replace sector = `i_sect' if _n == `i_n'
  replace newsitc = `i_ind' if _n == `i_n'
end

/* REDACTED: 
program fl_ind_sect is called to make ad-hoc updates to the respective variables 
*/
drop if newsitc == .

rename newsitc newind
append using "${dir_cw}/raw/sector_crosswalk.dta"
rename newind newsitc 

/* REDACTED 
Sector is updated for some instances */

isid newsitc

rename newsitc ch_ind_cw

save ${ds_cw}, replace

use "${dir_cw}/cw_ind_fk.dta", clear
append using "${dir_cw}/cw_ind_naics.dta"
append using "${dir_cw}/cw_ind_sic.dta"
keep ch_ind
duplicates drop

tostring ch_ind, force generate(ch_ind_cw)
replace ch_ind_cw=substr(ch_ind_cw,1,3) if length(ch_ind_cw)>4
destring ch_ind_cw, force replace
merge m:1 ch_ind_cw using ${ds_cw}

lab var ch_ind_cw ""
tab ch_ind ch_ind_cw if _merge != 3, miss
drop if _merge != 3
drop _merge

keep ch_ind sector
sort sector ch_ind

recast double ch_ind
replace ch_ind = round(ch_ind, 0.1)

save ${ds_cw}, replace
saveold ${ds_cw}_v12, replace
export delimited ${ds_cw}.csv, replace

di "Ended at $S_DATE $S_TIME"
// End of do file
